{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "2594e0ec",
   "metadata": {},
   "source": [
    "## 字典dict"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "48229c61",
   "metadata": {},
   "source": [
    "### 1.作用"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "44ad14aa",
   "metadata": {},
   "source": [
    "如果我们需要用一个变量记录多个值，但多个值是不同属性的，比如人的姓名、年龄、身高，用列表可以存，但列表是用索引对应值的，而索引不能明确地表示值的含义，这就用到字典类型，字典类型是用key：value形式来存储数据，其中key可以对value有描述性的功能\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "817eff8d",
   "metadata": {},
   "source": [
    "### 2.定义"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "7e637204",
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "invalid syntax (<ipython-input-4-21b6951596b0>, line 5)",
     "output_type": "error",
     "traceback": [
      "\u001b[0;36m  File \u001b[0;32m\"<ipython-input-4-21b6951596b0>\"\u001b[0;36m, line \u001b[0;32m5\u001b[0m\n\u001b[0;31m    >>> person_info={'name':'tony','age':18,'height':185.3}\u001b[0m\n\u001b[0m    ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n"
     ]
    }
   ],
   "source": [
    "# 定义：在{}内用逗号分隔开多元素，每一个元素都是key:value的形式，其中value可以是任意类型，而key则必须是不可变类型，详见第八小节，通常key应该是str类型，因为str类型会对value有描述性的功能\n",
    "info={'name':'tony','age':18,'sex':'male'} #本质info=dict({....})\n",
    "# 也可以这么定义字典\n",
    "info=dict(name='tony',age=18,sex='male') # info={'age': 18, 'sex': 'male', 'name': 'tony'}\n",
    ">>> person_info={'name':'tony','age':18,'height':185.3}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "71110c38",
   "metadata": {},
   "source": [
    "### 3.使用"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "1c952c2f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'sleep'"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 1、字典类型是用key来对应值，key可以对值有描述性的功能，通常为字符串类型\n",
    ">>> person_info={'name':'tony','age':18,'height':185.3}\n",
    ">>> person_info['name']\n",
    "'tony'\n",
    ">>> person_info['age']\n",
    "18\n",
    ">>> person_info['height']\n",
    "185.3\n",
    "# 2、字典可以嵌套，嵌套取值如下\n",
    ">>> students=[\n",
    "... {'name':'tony','age':38,'hobbies':['play','sleep']},\n",
    "... {'name':'jack','age':18,'hobbies':['read','sleep']},\n",
    "... {'name':'rose','age':58,'hobbies':['music','read','sleep']},\n",
    "... ]\n",
    ">>> students[1]['hobbies'][1] #取第二个学生的第二个爱好\n",
    "'sleep'"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9645430d",
   "metadata": {},
   "source": [
    "#### 优先掌握的操作"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "ceccc5e1",
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "invalid syntax (<ipython-input-5-f3d2e704e60a>, line 3)",
     "output_type": "error",
     "traceback": [
      "\u001b[0;36m  File \u001b[0;32m\"<ipython-input-5-f3d2e704e60a>\"\u001b[0;36m, line \u001b[0;32m3\u001b[0m\n\u001b[0;31m    >>> dic = {\u001b[0m\n\u001b[0m    ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n"
     ]
    }
   ],
   "source": [
    "# 1、按key存取值：可存可取\n",
    "# 1.1 取\n",
    ">>> dic = {\n",
    "...     'name': 'xxx',\n",
    "...     'age': 18,\n",
    "...     'hobbies': ['play game', 'basketball']\n",
    "... }\n",
    ">>> dic['name']\n",
    "'xxx'\n",
    ">>> dic['hobbies'][1]\n",
    "'basketball'\n",
    "# 1.2 对于赋值操作，如果key原先不存在于字典，则会新增key:value\n",
    ">>> dic['gender'] = 'male'  \n",
    ">>> dic\n",
    "{'name': 'tony', 'age': 18, 'hobbies': ['play game', 'basketball'],'gender':'male'}\n",
    "# 1.3 对于赋值操作，如果key原先存在于字典，则会修改对应value的值\n",
    ">>> dic['name'] = 'tony'\n",
    ">>> dic\n",
    "{'name': 'tony', 'age': 18, 'hobbies': ['play game', 'basketball']}\n",
    "\n",
    "\n",
    "# 2、长度len\n",
    ">>> len(dic) \n",
    "3\n",
    "\n",
    "\n",
    "# 3、成员运算in和not in\n",
    ">>> 'name' in dic  # 判断某个值是否是字典的key\n",
    "True\n",
    "\n",
    "\n",
    "# 4、删除\n",
    ">>> dic.pop('name')  # 通过指定字典的key来删除字典的键值对\n",
    ">>> dic\n",
    "{'age': 18, 'hobbies': ['play game', 'basketball']}\n",
    "\n",
    "\n",
    "# 5、键keys()，值values()，键值对items()\n",
    ">>> dic = {'age': 18, 'hobbies': ['play game', 'basketball'], 'name': 'xxx'}\n",
    "# 获取字典所有的key\n",
    ">>> dic.keys()  \n",
    "dict_keys(['name', 'age', 'hobbies'])\n",
    "# 获取字典所有的value\n",
    ">>> dic.values()\n",
    "dict_values(['xxx', 18, ['play game', 'basketball']])\n",
    "# 获取字典所有的键值对\n",
    ">>> dic.items()\n",
    "dict_items([('name', 'xxx'), ('age', 18), ('hobbies', ['play game', 'basketball'])])\n",
    "\n",
    "\n",
    "# 6、循环\n",
    "# 6.1 默认遍历的是字典的key\n",
    ">>> for key in dic:\n",
    "...     print(key)\n",
    "... \n",
    "age\n",
    "hobbies\n",
    "name\n",
    "# 6.2 只遍历key\n",
    ">>> for key in dic.keys():\n",
    "...     print(key)\n",
    "... \n",
    "age\n",
    "hobbies\n",
    "name\n",
    "# 6.3 只遍历value\n",
    ">>> for key in dic.values():\n",
    "...     print(key)\n",
    "... \n",
    "18\n",
    "['play game', 'basketball']\n",
    "xxx\n",
    "# 6.4 遍历key与value\n",
    ">>> for key in dic.items():\n",
    "...     print(key)\n",
    "... \n",
    "('age', 18)\n",
    "('hobbies', ['play game', 'basketball'])\n",
    "('name', 'xxx')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0c0edf92",
   "metadata": {},
   "source": [
    "### 基础操作"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "8baeaccf",
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "invalid syntax (<ipython-input-6-4e8b177045a1>, line 1)",
     "output_type": "error",
     "traceback": [
      "\u001b[0;36m  File \u001b[0;32m\"<ipython-input-6-4e8b177045a1>\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m    1.get()\u001b[0m\n\u001b[0m      ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n"
     ]
    }
   ],
   "source": [
    "1.get()\n",
    "\n",
    ">>> dic= {'k1':'jason','k2':'Tony','k3':'JY'}\n",
    ">>> dic.get('k1')\n",
    "'jason'  # key存在，则获取key对应的value值\n",
    ">>> res=dic.get('xxx') # key不存在，不会报错而是默认返回None\n",
    ">>> print(res)\n",
    "None  \n",
    ">>> res=dic.get('xxx',666) # key不存在时，可以设置默认返回的值\n",
    ">>> print(res)\n",
    "666 \n",
    "# ps:字典取值建议使用get方法\n",
    "2.pop()\n",
    "\n",
    ">>> dic= {'k1':'jason','k2':'Tony','k3':'JY'}\n",
    ">>> v = dic.pop('k2')  # 删除指定的key对应的键值对,并返回值\n",
    ">>> dic\n",
    "{'k1': 'jason', 'kk2': 'JY'}\n",
    ">>> v\n",
    "'Tony'\n",
    "3.popitem()\n",
    "\n",
    ">>> dic= {'k1':'jason','k2':'Tony','k3':'JY'}\n",
    ">>> item = dic.popitem()  # 随机删除一组键值对,并将删除的键值放到元组内返回\n",
    ">>> dic\n",
    "{'k3': 'JY', 'k2': 'Tony'}\n",
    ">>> item\n",
    "('k1', 'jason')\n",
    "4.update()\n",
    "\n",
    "# 用新字典更新旧字典，有则修改，无则添加\n",
    ">>> dic= {'k1':'jason','k2':'Tony','k3':'JY'}\n",
    ">>> dic.update({'k1':'JN','k4':'xxx'})\n",
    ">>> dic\n",
    "{'k1': 'JN', 'k3': 'JY', 'k2': 'Tony', 'k4': 'xxx'}\n",
    "5.fromkeys()\n",
    "\n",
    ">>> dic = dict.fromkeys(['k1','k2','k3'],[])\n",
    ">>> dic\n",
    "{'k1': [], 'k2': [], 'k3': []}\n",
    "6.setdefault()\n",
    "\n",
    "# key不存在则新增键值对，并将新增的value返回\n",
    ">>> dic={'k1':111,'k2':222}\n",
    ">>> res=dic.setdefault('k3',333)\n",
    ">>> res\n",
    "333\n",
    ">>> dic # 字典中新增了键值对\n",
    "{'k1': 111, 'k3': 333, 'k2': 222}\n",
    "\n",
    "# key存在则不做任何修改，并返回已存在key对应的value值\n",
    ">>> dic={'k1':111,'k2':222}\n",
    ">>> res=dic.setdefault('k1',666)\n",
    ">>> res\n",
    "111\n",
    ">>> dic # 字典不变\n",
    "{'k1': 111, 'k2': 222}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "028b9545",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
